package com.zsr.web;

import com.zsr.pojo.User;
import com.zsr.service.UserService;
import com.zsr.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistServlet extends HttpServlet {

    UserService userService =new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String email = req.getParameter("email");

        //2.检查验证码
        if("abcd".equalsIgnoreCase(code)){
            //3.检查 用户名是否可用
            if(userService.existsUsername(username)){
                System.out.println("用户名["+username+"]已存在！");

                req.setAttribute("msg","用户名["+username+"]已存在！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                req.setAttribute("code",code);

                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);

            }else{
                 userService.registerUser(new User(null,username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else{
            System.out.println("验证码错误");

            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            req.setAttribute("code",code);

            //获取请求转发器对象，该转发器的指向通过getRequestDisPatcher()的参数设置
            //调用forward()方法，转发请求
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }
}
